package com.demo.util;

import javax.jms.Connection;
import javax.jms.ConnectionFactory;
import javax.jms.DeliveryMode;
import javax.jms.Destination;
import javax.jms.JMSException;
import javax.jms.MessageProducer;
import javax.jms.Session;
import javax.jms.TextMessage;

import org.apache.activemq.ActiveMQConnectionFactory;

public class Publisher {

	// ConnectionFactory ：连接工厂，JMS 用它创建连接
    protected static transient ConnectionFactory factory;  
    // Connection ：JMS 客户端到JMS Provider 的连接
    protected transient Connection connection;  
    // Session： 一个发送或接收消息的线程
    protected transient Session session;
    // MessageProducer：消息发送者
    protected transient MessageProducer producer;
    // Destination ：消息的目的地;消息发送给谁.
    protected transient Destination destination;
    
    private static final int SEND_NUMBER = 5;
	
	private static final String DEFAULT_USERNAME = "admin";
	
	private static final String DEFAULT_PASSWORD = "admin";
	/**
	 * @param username 用户名
	 * @param password 密码
	 * @param brokerurl url
	 * @throws JMSException
	 */
	public Publisher(String username,String password,String brokerurl) throws JMSException {
		// 构造ConnectionFactory实例对象，此处采用ActiveMq的实现jar
	        factory = new ActiveMQConnectionFactory(username,password,brokerurl);  
	        connection = factory.createConnection();  
	        try {  
	        connection.start();  
	        } catch (JMSException jmse) {  
	            connection.close();  
	            throw jmse;  
	        }  
	        session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);  
	       // producer = session.createProducer(null);  
	  }  
	
	/**
	 * @param username 用户名
	 * @param password 密码
	 * @param brokerurl url
	 * @throws JMSException
	 */
	public Publisher(String brokerurl) throws JMSException {  
		// 构造ConnectionFactory实例对象，此处采用ActiveMq的实现jar
	        factory = new ActiveMQConnectionFactory(DEFAULT_USERNAME,DEFAULT_PASSWORD,brokerurl);  
	        connection = factory.createConnection();  
	        try {  
	        connection.start();  
	        } catch (JMSException jmse) {  
	            connection.close();  
	            throw jmse;  
	        }  
	        session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);  
	       // producer = session.createProducer(null);  
	  }  
	
	public void send(String queue,int type,String str){
        try {
            // 获取session注意参数值xingbo.xu-queue是一个服务器的queue，须在在ActiveMq的console配置
            destination = session.createQueue(queue);
            // 得到消息生成者【发送者】
            producer = session.createProducer(destination);
            // 设置不持久化，此处学习，实际根据项目决定
            producer.setDeliveryMode(DeliveryMode.PERSISTENT);
            // 构造消息，此处写死，项目就是参数，或者方法获取
            sendMessage(session, producer,type,str);
           // session.commit();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (null != connection)
                    connection.close();
            } catch (Throwable ignore) {
            }
        }
    }

    public static void sendMessage(Session session, MessageProducer producer,int type,String str) throws Exception {
    	TextMessage message = null;
            if(type==1){
            	/*JSONObject json = new JSONObject();
	           	 json.put("email", "hezuodong2967@163.com");
	   	         json.put("subject", "测试邮件主题"+i);
	   	         json.put("content", "测试邮件内容"+i);*/
            	System.out.println(str);
	   	          message = session
   	                    .createTextMessage(str);
            }else{
            	  message = session
    	                    .createTextMessage(str);
            }
            System.out.println("发送消息：" + message);
            producer.send(message);
    }
    
    public void close() throws JMSException {  
        if (connection != null) {  
            connection.close();  
        }  
    }  
    public static void main(String[] args) throws JMSException {
    	Publisher pu = null;
    	if("hezuodong".equals(args[0])){
    		 pu = new Publisher("tcp://192.168.2.62:61616");
    		Mail mail = new Mail("2321837666@qq.com", 1, getMail());
    		pu.send("SendMail", 1, mail.toString());
    	}else if("liuguoqiang".equals(args[0])){
    		 pu = new Publisher("admin","123456","tcp://192.168.2.14:61616");
    		MobileCode mo = new MobileCode("13552140385",RandomUtils.getRandomCode());
    		pu.send("SendMobile",2,mo.toString());
    	}
		pu.close();
	}
    
    public static String getMail(){
    	StringBuilder sb = new StringBuilder();
    	sb.append("尊敬的用户您好，验证码为:").append(RandomUtils.getRandomCode()).append("，请妥善保存。【爱理财】");
    	String shtml = "<html><head></head><body><h1>Hello</h1>" + "<h3>"+sb.toString()+"</h3>"  
                + "</body></html>";  
    	return shtml;
    }
}
